import cv2
import numpy as np
import matplotlib.pyplot as plt

# 读取图像
image = cv2.imread('image.jpg')

# 初始化掩码
mask = np.zeros(image.shape[:2], np.uint8)

# 初始化背景和前景模型
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)

# 定义矩形框（左上角和右下角的坐标）
rect = (50, 50, 450, 290)

# 应用GrabCut算法
cv2.grabCut(image, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)

# 创建新的掩码，将可能的前景和确定的前景标记为1
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')

# 提取前景
foreground = image * mask2[:, :, np.newaxis]

# 定义结构元素
kernel = np.ones((3, 3), np.uint8)

# 膨胀操作
foreground_dilated = cv2.dilate(foreground, kernel, iterations=1)

# 腐蚀操作
foreground_eroded = cv2.erode(foreground, kernel, iterations=1)

# 显示结果
plt.figure(figsize=(15, 5))

plt.subplot(1, 3, 1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('Original Image')

plt.subplot(1, 3, 2)
plt.imshow(cv2.cvtColor(foreground, cv2.COLOR_BGR2RGB))
plt.title('GrabCut Result')

plt.subplot(1, 3, 3)
plt.imshow(cv2.cvtColor(foreground_eroded, cv2.COLOR_BGR2RGB))
plt.title('Post-processed Result')

plt.show()